module manager {

    export class ShareManager extends egret.EventDispatcher {

        public static readonly FAIL: number = 0;

        public static readonly SUCC: number = 1;

        public static readonly SHARE_STATUS: string = "share_status";

        private static _instance: ShareManager;

        public shareOpened: boolean = false;

        private hidedAt: number;

        private failedTimes: number = 0;

        public static getInstance(): ShareManager {
            if (ShareManager._instance == null) {
                ShareManager._instance = new ShareManager();
            }
            return ShareManager._instance;
        }

        public constructor() {
            super();
        }

        public init(): void {
            let that = this;
            if (!GameManager.isProduct) {
                return;
            }
            wx.onShow(res => {
                egret.log("开始显示界面");
                if (this.checkPkInvite(res)) {
                    this.showInviteTip(res, manager.LaunchOptionsManager.getOptionValue(res.query, "room_id"));
                } else if (that.checkGroupRank(res)) {

                } else if (that.checkCommonShare(res)) {

                } else {

                }
            });

            wx.onHide(function () {
                egret.log("开始隐藏界面");
                manager.ShareManager.getInstance().shareOpened = true;
                manager.ShareManager.getInstance().hidedAt = new Date().getTime();
                // manager.StatisticsManager.hideAtScene(manager.StatisticsManager.sceneId);
            });
        }

        private checkPkInvite(res: any): boolean {
            let roomId: string = manager.LaunchOptionsManager.getOptionValue(res.query, "room_id");
            return roomId.length > 0;
        }

        private showInviteTip(res: any, roomId: string): void {
            egret.log("roomId:", roomId);
            let isSelf = (manager.GameManager.getInstance().openid == manager.LaunchOptionsManager.getOptionValue(res.query, "wechatId"));
            let invitePkPage: game.InviteTipPage = new game.InviteTipPage(roomId, isSelf);
            manager.GameManager.getInstance().getUIManager().addGameWidget(invitePkPage);
        }

        private checkGroupRank(res: any): boolean {
            egret.log("分享数据:", res);
            let groupRank: number = parseInt(res.query.group_rank || "0");
            let shareTicket: string = res.shareTicket || "";
            if (groupRank > 0 && shareTicket.length > 5) {
                egret.log("群排行分享成功");
                let event: events.SceneEvent = new events.SceneEvent(game.SceneIds.RANK_SCENE_ID, {
                    isShowGroup: true,
                    shareTicket: shareTicket
                }, events.SceneEvent.POPUP_SHOW_TYPE);
                facade.GameFacade.getInstance().dispatchEvent(event);
                return true;
            }
            return false;
        }

        private checkCommonShare(res: any): boolean {
            egret.log("分享数据:", res);
            let commonShare: number = parseInt(res.query.common_share || "0");

            if (GameManager.COMMON_SHARE < 1) {
                return false;
            }
            GameManager.COMMON_SHARE = 0;
            let current: number = new Date().getTime();
            let hidedAt: number = manager.ShareManager.getInstance().hidedAt;
            let timeDiff: number = (current - hidedAt) / 1000;
            egret.log("时间差:", timeDiff);

            if (timeDiff < 3) {
                manager.ShareManager.getInstance().failedTimes += 1;
                if (manager.ShareManager.getInstance().failedTimes > 1) {
                    manager.ShareManager.getInstance().failedTimes = 0;
                    manager.ShareManager.getInstance().dispatchEvent(new egret.Event(ShareManager.SHARE_STATUS,
                        false, false, ShareManager.SUCC));
                    egret.log("分享次数大于2次");
                } else {
                    manager.ShareManager.getInstance().dispatchEvent(new egret.Event(ShareManager.SHARE_STATUS,
                        false, false, ShareManager.FAIL));
                    egret.log("分享失败");
                    wx.showModal({
                        title: '提示',
                        content: '由于网络波动原因，分享失败，请重试',
                        confirmText: "立刻分享",
                        showCancel: false,
                        success: res => {
                            if (res.confirm) {
                                manager.GameManager.getInstance().commonShare();
                            } else if (res.cancel) {
                            }
                        },
                        complete: function (res) {
                        }
                    });
                }
            } else {
                egret.log("分享超过3秒时间->成功:", timeDiff);
                manager.ShareManager.getInstance().dispatchEvent(new egret.Event(ShareManager.SHARE_STATUS,
                    false, false, ShareManager.SUCC));
            }
            return false;
        }

        public savePhoto(posterScale: number) {
            let canvas = SystemManager.getSharedCanvas();
            canvas.toTempFilePath({
                x: 0,
                y: 0,
                width: canvas.width,
                height: canvas.height,
                success(res) {
                    let path0 = res.tempFilePath;
                    console.log(path0)
                    wx.saveImageToPhotosAlbum({
                        filePath: path0,
                        success(res) {
                            console.log("成功保存到相册");
                            wx.showToast({
                                title: "分享图已保存到相册,快去朋友圈分享战绩！"
                            });
                        },
                        fail: function (res) {
                            console.log("WxPlatform >> saveImageToPhotosAlbum fail")
                        }
                    })
                }
            })
        }

    }

}